package com.abu.message.listener;

import cn.hutool.core.util.StrUtil;
import com.abu.message.utils.CodeUtil;
import com.abu.message.utils.QQMailTemplate;
import com.abu.message.utils.SmsTemplate;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ForgetMessageListener {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private QQMailTemplate mailTemplate;

    private static final String PHONE_CODE_FORGET_EXCHANGE = "PHONE_CODE_FORGET_EXCHANGE";
    private static final String PHONE_CODE_FORGET_ROUTING = "PHONE_CODE_FORGET_ROUTING";

    private static final String FORGET_PREFIX = "SECORT_FORGET:";

    /**
     * 普通用户注册验证码
     *
     * @param
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "PHONE_CODE_FORGET_QUEUE", ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(name = PHONE_CODE_FORGET_EXCHANGE, ignoreDeclarationExceptions = "true", type = "direct"),
            key = {PHONE_CODE_FORGET_ROUTING}
    ))
    public void sendMsg(HashMap<String, String> receiveMap) {
        String type = receiveMap.get("type");
        String sendTo = receiveMap.get("sendTo");
//        判断type类型，如果是1，则是手机号发送验证码，2，则是邮箱发送验证码
        String code = CodeUtil.generator(4);
//        发送验证码到邮箱(2)或者手机上(1)
        switch (type) {
            case "1": {
                try {
                    SmsTemplate.sendMsg(sendTo, code);
                } catch (ClientException e) {
                    log.error("发送验证码失败");
                }
                break;
            }
            case "2": {
                String title = "《阿布校理》";
                this.mailTemplate.sendMailMsg("您的验证码为：" + code, title, sendTo);
                break;
            }
            default:
                break;
        }
//        将数据放在缓存中
//        缓存中验证码前缀是SECORD_FORGET:手机号
        this.stringRedisTemplate.opsForValue().set(FORGET_PREFIX + sendTo, code);
    }
}
